package com.kolon.business.mngr.service.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.business.mngr.service.dao.ServiceDao;
import com.kolon.framework.constant.Constant;
import com.kolon.framework.file.DefaultFileRenamePolicy;
import com.kolon.framework.file.FileUtil;
import com.kolon.framework.file.UploadedFile;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mngr.service.controller.ServiceModifyController")
public class ServiceModifyController implements SimpleController {

	@Resource(name="com.kolon.business.mngr.service.dao.ServiceDaoImpl")
	private ServiceDao serviceDao;
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/business/mngr/service/serviceModify.do")
	public ModelAndView controller(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Map<String, String> map = new HashMap<String, String>();
		List<UploadedFile> fileList = new ArrayList<UploadedFile>();
		UploadedFile imgFile = null;
		// 파라미터
		int page = ComUtil.sToi(ComUtil.nullChk(request.getParameter("page"), "1"));
		String servNo = ComUtil.nullChk(request.getParameter("servNo"));
		String schTp = ComUtil.nullChk(request.getParameter("schTp"));
		String schTxt = ComUtil.nullChk(request.getParameter("schTxt"));
		String appNm = ComUtil.nullChk(multiRequest.getParameter("appNm"));
		String frfVer = multiRequest.getParameter("frfVer");
		map.put("servNo", servNo);
		map.put("servNm", ComUtil.nullChk(multiRequest.getParameter("servNm"), "없음"));
		map.put("servDesc", multiRequest.getParameter("servDesc"));
		map.put("lnkUrl", multiRequest.getParameter("lnkUrl"));
		map.put("tagNm", multiRequest.getParameter("tagNm"));
		map.put("cpyCd", "A".equals(multiRequest.getParameter("cpyCd")) ? null : "B");
		map.put("sortNum", multiRequest.getParameter("sortNum"));
		map.put("exYn", multiRequest.getParameter("exYn"));
		map.put("appNm", appNm);
		map.put("useYn", ComUtil.nullChk(multiRequest.getParameter("useYn"), "Y"));
		map.put("appDesc", ComUtil.nullChk(multiRequest.getParameter("appDesc")));
		map.put("frfVer", frfVer);
		// 회원 세션 정보
		HttpSession httpSession = multiRequest.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_MNGR_INFO);
		map.put("mdfyId", (String)userMap.get("MNGR_ID"));
		// 서비스 정보 조회
		Map servMap = serviceDao.getMap(map);
		if (servMap == null)
			return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
		String servTp = ComUtil.oTos(servMap.get("SERV_TP"));
		String fdrNm = ComUtil.oTos(servMap.get("FDR_NM"));
		map.put("servTp", servTp);
		map.put("fdrNm", fdrNm);
		// 아이콘 및 앱 파일 저장 경로
		String servIconPath = MsgUtil.getMessage("service.icon.path");
		String appFilePath = MsgUtil.getMessage("app.file.path");
		appFilePath = appFilePath + ComUtil.oTos(servMap.get("FRF_TP")).toLowerCase() 
			+ File.separator + fdrNm + File.separator;
		// 웹이 아닐 시 중복 체크 함
		if (!"A".equals(servTp)) {
			if (!appNm.equals(servMap.get("APP_NM"))) {
				if (serviceDao.getAppNmCnt(map) > 0)
					return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
			}
			if (!frfVer.equals(servMap.get("FRF_VER"))) {
				if (serviceDao.getAppHstyCnt(map) > 0)
					return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
			}
		}
		// STEP START
		try {
			// STEP 01. 이미지 파일 업로드
			imgFile = FileUtil.fileUpload(multiRequest.getFile("imgNm"), servIconPath, 
					new DefaultFileRenamePolicy());
			map.put("imgNm", imgFile.getFileName());
			// STEP 02. 업로드 했을 경우 기존 파일 삭제
			if (!"".equals(imgFile.getFileName()))
				FileUtil.delFile(servIconPath + servMap.get("IMG_NM"));
			// STEP 03. 앱 파일 업로드
			for (int i=1; i<=3; i++) {
				MultipartFile mFile = multiRequest.getFile("appFile"+i);
				// 업로드 시 기존 파일 삭제
				if (!"".equals(mFile.getOriginalFilename()))
					FileUtil.delFile(appFilePath + servMap.get("FILE_S_NM_"+i));
				UploadedFile uploadedFile = FileUtil.fileUpload(mFile, 
						appFilePath, new DefaultFileRenamePolicy());
				map.put("fileRNm"+i, uploadedFile.getFileRealName());
				map.put("fileSNm"+i, uploadedFile.getFileName());
				map.put("fileTp"+i, uploadedFile.getExtension());
				map.put("fileSize"+i, String.valueOf(uploadedFile.getSize()));
				fileList.add(uploadedFile);
			}
			// STEP 04. 서비스 정보 수정
			serviceDao.update(map);
		} catch (Exception e) {
			// 예외 발생 시 업로드 된 파일을 삭제
			if (imgFile != null)
				FileUtil.delFile(servIconPath + imgFile.getFileName());
			for (int i=0, size=fileList.size(); i<size; i++)
				FileUtil.delFile(appFilePath + fileList.get(i).getFileName());
		}
		// 리턴
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("redirect:/business/mngr/service/serviceView.do");
		modelAndView.addObject("servNo", servNo);
		modelAndView.addObject("page", page);
		modelAndView.addObject("schTp", schTp);
		modelAndView.addObject("schTxt", schTxt);
		return modelAndView;
	}
}
